<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane label="换线时间报表搜索"> </el-tab-pane>
      <avue-form ref="form" :option="option" v-model="form">
        <template slot="btn">
          <el-button type="primary" size="small" class="el-icon-search" @click="handleSubmit">搜索</el-button>
          <el-button size="small" class="el-icon-delete" @click="handleCancel">清空</el-button>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="chart-tab tab-font">
      <el-tab-pane label="换线时间报表明细"> </el-tab-pane>
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="chart-content">
            <chart-view :chart-option="chartOption" :auto-resize="true" width="95%" height="370px" />
            <el-tooltip content="箭头前为换线前产品，箭头后为新生产产品" placement="top">
              <span class="xaxis"><i class="el-icon-info"></i>换线产品名称/日期 </span>
            </el-tooltip>
          </div>
          <avue-crud :option="tableOption" :table-loading="loading" :data="data" :page.sync="tablePage" @current-change="currentChange" @size-change="sizeChange" ref="crud">
            <template slot="menuLeft">
              <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport" :loading="exportBtnLoading">导出 </el-button>
            </template>
          </avue-crud>
        </el-col>
      </el-row>
    </el-tabs>
  </basic-container>
</template>

<script>
import ChartView from '@/components/chart/index.vue';
import moment from 'moment';
import { tableOption, option } from '@/views/report/changeLineReport.js';
import 'echarts/lib/component/dataZoom';
import { findProductionlineList } from '@/api/product/workorder';
import { exportChangeLineReportData, getChangeLineReportChartData, getChangeLineReportData } from '@/api/report/report';
import { exportReportData } from '@/api/admin/reportConfig';
export default {
  name: 'changeLineReport',
  components: {
    ChartView
  },
  data() {
    return {
      tableOption,
      option,
      loading: false,
      data: [],
      exportData: [],
      exportBtnLoading: false,
      form: {
        examineDate: this.getDefaultTime()
      },
      tablePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      /*
         [
         [], [], [],
         [], [], [],
         [], [], [],
         [], [], [],
         [], [], []
         ]
         arr[x][] 是柱子个数
         */
      chartOption: {
        grid: {
          top: '10%',
          left: '4%',
          right: '4%',
          bottom: '30%',
          containLabel: false
        },
        xAxis: {
          type: 'category',
          name: '',
          triggerEvent: true,
          data: [],
          axisLabel: {
            show: true,
            interval: 0,
            margin: 40,
            rotate: -90
          }
        },
        tooltip: {
          trigger: 'axis',
          triggerOn: 'mousemove',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(50, 50, 50, 0.7)',
          borderColor: '#333',
          textStyle: {
            color: '#fff'
          },
          formatter: (params) => {
            let tooltipHtml = '<div class="custom-tooltip">';
            for (let i = 0; i < params.length; i++) {
              tooltipHtml +=
                '<div>' +
                '<span>' +
                '换线总时间:' +
                params[i].data.formData.duration +
                '分钟' +
                '</span>' +
                '<br/><br/>' +
                '<span>' +
                '上一产品编码:' +
                params[i].data.formData.prePartName +
                '</span>' +
                '<br/>' +
                '<span>' +
                '上一产品工单:' +
                params[i].data.formData.preWorkOrderNo +
                '</span>' +
                '<br/><br/>' +
                '<span>' +
                '换线后产品编码:' +
                params[i].data.formData.currPartName +
                '</span>' +
                '<br/>' +
                '<span>' +
                '换线后产品工单:' +
                params[i].data.formData.currWorkOrderNo +
                '</span>' +
                '<br/>';
            }
            tooltipHtml += '</div></div>';
            return tooltipHtml;
          }
        },
        yAxis: {
          type: 'value',
          name: '换线总时间/分'
        },
        series: [],
        dataZoom: [
          {
            type: 'slider',
            xAxisIndex: 0,
            start: 0,
            end: 50,
            minSpan: 20,
            bottom: 20
          }
        ]
      }
    };
  },
  mounted() {
    this.getProductionLineList();
  },
  methods: {
    async onLoad(isDrawChart = true) {
      const params = this.getQueryParameter(true);
      try {
        this.loading = true;
        const res = await getChangeLineReportData(params);
        const data = res.data.data;
        this.data = data.records;
        this.tablePage = {
          total: data.total,
          currentPage: data.current
        };
        if (isDrawChart) {
          this.setChartOption();
        }
      } catch (e) {
      } finally {
        this.loading = false;
      }
    },
    currentChange(currentPage) {
      this.tablePage.currentPage = currentPage;
      this.onLoad(false);
    },
    sizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      this.onLoad(false);
    },
    getQueryParameter(isNeedPage) {
      const { examineDate, lineId } = this.form;
      const { currentPage, pageSize } = this.tablePage;
      return isNeedPage
        ? {
            lineId: lineId,
            startTime: this.$moment(new Date(examineDate[0])).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            endTime: this.$moment(new Date(examineDate[1])).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
            size: pageSize,
            current: currentPage
          }
        : {
            lineId: lineId,
            startTime: this.$moment(new Date(examineDate[0])).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            endTime: this.$moment(new Date(examineDate[1])).endOf('day').format('YYYY-MM-DD HH:mm:ss')
          };
    },
    //
    async handleExport() {
      const params = this.getQueryParameter(false);
      try {
        this.exportBtnLoading = true;
        const res = await exportChangeLineReportData(params);
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=UTF-8' });
        const fileName = `换线时间报表.xlsx`;
        const link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.append(link);
        link.click();
        URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      } catch (e) {
        console.log(e);
        this.$message.error('系统错误，请联系管理员');
      } finally {
        this.exportBtnLoading = false;
      }
    },
    handleSubmit(form, done) {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          this.onLoad(true);
          done();
        }
      });
    },
    handleCancel() {
      this.tablePage.currentPage = 1;
      this.tablePage.total = 0;
      this.$refs.form.resetForm();
      this.form = {};
      this.$set(this.chartOption, 'series', []);
      this.data = [];
      // this.onLoad(false);
    },
    getDefaultTime() {
      return [this.$moment(new Date()).subtract(7, 'days').format('yyyy-MM-DD'), this.$moment(new Date()).subtract(1, 'days').format('yyyy-MM-DD')];
    },
    getProductionLineList() {
      findProductionlineList().then((res) => {
        const column = this.findObject(this.option.column, 'lineId');
        column.dicData = this._map(this._get(res, 'data.data', []), (item) => {
          return { label: item.name, value: item.id };
        });
        // this.productionlineList = this._get(res, 'data.data', []);
      });
    },
    async setChartOption() {
      // 获取数据
      const data = await this.getChartData();
      //产品b->产品a 随机生成颜色,并且同种’产品b->产品a‘为同种颜色
      const colorMap = this.getProductionColor(data);
      const cloneData = this._cloneDeep(data);
      // const xAxis = this.getXAxis(cloneData);
      const xAxis = this.getXAxis(cloneData);
      const chartData = this.getChartOptionData(cloneData, colorMap);
      const series = this.getSeries(this._cloneDeep(chartData));
      const zoom = this.getZoom(data);
      this.$set(this.chartOption, 'xAxis', xAxis);
      this.$set(this.chartOption, 'series', series);
      this.$set(this.chartOption, 'dataZoom', zoom);
      // 设置数据
    },
    getChartOptionData(chartData, colorMap) {
      const data = [];
      chartData.forEach((item, index) => {
        const chartName = `${item.windowTime}:${item.prePartName}->${item.currPartName}`;
        data.push({
          value: Number(item.duration),
          formData: {
            currWorkOrderNo: item.currWorkOrderNo || '',
            preWorkOrderNo: item.preWorkOrderNo || '',
            duration: item.duration,
            prePartName: item.prePartName,
            currPartName: item.currPartName
          },
          // name: item.chartName || '',
          itemStyle: {
            // opacity: Number(item.duration) > 0 ? 1 : 0,
            color: colorMap[item.chartName]
          }
        });
      });
      return data;
      // const longestLength = this.getLongestLength(chartData);
      // const xAxisData = Array.from(new Set(chartData.map((item) => item.windowTime)));
      // const deepLength = xAxisData.length || 0;
      // const recordId = [];
      // const arr = new Array(longestLength).fill(0);
      // for (let i = 0; i < longestLength; i++) {
      //   // 2
      //   const dataItem = new Array(deepLength).fill(0);
      //   for (let j = 0; j < deepLength; j++) {
      //     // 3
      //     for (let k = 0; k < chartData.length; k++) {
      //       const item = chartData[k];
      //       if (!recordId.includes(item.id) && xAxisData[j] === chartData[k].windowTime) {
      //         dataItem[j] = {
      //           value: item.duration,
      //           name: item.chartName || '',
      //           itemStyle: {
      //             opacity: Number(item.duration) > 0 ? 1 : 0,
      //             color: this.getProductionColor(chartData)[item.chartName]
      //           },
      //           label: {
      //             show: true,
      //             rotate: -20,
      //             distance: 40,
      //             offset: [40, -30] //表示文字在[横向上偏移 30，纵向上偏移 40]
      //           }
      //         };
      //         recordId.push(item.id);
      //         break;
      //       }
      //     }
      //   }
      //   arr[i] = this._cloneDeep(dataItem);
      // }
      // return arr;
    },
    async getChartData() {
      const params = this.getQueryParameter(false);
      try {
        this.loading = true;
        const res = await getChangeLineReportChartData(params);
        const data = res.data.data;
        data.sort((a, b) => {
          return new Date(a.windowTime) - new Date(b.windowTime);
        });
        return data;
      } catch (e) {
      } finally {
        this.loading = false;
      }
    },
    getProductionColor(data) {
      const colorMap = {};
      data.forEach((el) => {
        const chartName = `${el.windowTime}:${el.prePartName}->${el.currPartName}`;
        el.chartName = chartName;
        if (!(chartName in colorMap)) {
          colorMap[chartName] = this.getRandomColor();
        }
      });
      return colorMap;
    },
    // 生成随机颜色的方法
    getRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
    // 获取xAxis
    getXAxis(arr) {
      return {
        type: 'category',
        triggerEvent: true,
        axisLabel: {
          show: true,
          interval: 0,
          formatter: function (value) {
            // 在需要换行的地方添加 \n
            return value.split(':').join('\n').split('->').join('\n↓\n');
          }
        },
        data: arr.map((el, index) => `${el.windowTime}:${el.prePartName}->${el.currPartName}`)
      };
      // return {
      //   type: 'category',
      //   data: arr.map((el) => `${el.windowTime}牛逼的日期${el.prePartName}->${el.currPartName}`),
      //   //     data: Array.from(new Set(data.map((item) => item.windowTime))),
      //   axisLabel: {
      //     interval: 0,
      //     margin: 40
      //   }
      // };
    },
    // 获取series
    getSeries(chartData) {
      return {
        type: 'bar',
        barWidth: '%',
        large: true,
        barMinHeight: 1,
        barMinWidth: 40,
        barMaxWidth: 41,
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        },
        data: chartData
      };
    },
    // 获取zoom
    getZoom(data) {
      const SHOW_DATA_LENGTH = 7;
      const length = data.length;
      const zoomLength = Math.floor((7 * 100) / length);
      return [
        {
          type: 'inside',
          xAxisIndex: 0,
          start: 0,
          end: length === 0 ? 100 : zoomLength,
          minSpan: length === 0 ? 100 : zoomLength,
          bottom: 20
        },
        {
          type: 'slider',
          xAxisIndex: 0,
          start: 0,
          end: length === 0 ? 100 : zoomLength,
          minSpan: length === 0 ? 100 : zoomLength,
          bottom: 20
        }
      ];
    }
  }
};
</script>

<style scoped lang="scss">
.chart-tab {
  margin-top: 24px;
  height: calc(100vh - 350px);
  overflow-y: scroll;
}
.chart-content {
  position: relative;
}
.xaxis {
  position: absolute;
  font-size: 12px;
  right: 3px;
  bottom: 105px;
  z-index: 999;
}
.chart-header {
  display: flex;
  justify-content: center;
  align-items: center;
}
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
</style>
